/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ocr.mpp;

import cn.ac.iie.di.ocr.util.GlobalParameters;
import cn.ac.iie.di.ocr.util.MppJdbcPool_dbcp;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javafx.scene.input.KeyCode;

/**
 *
 * @author Austin
 */
public class UpdateMppThreadBak implements Runnable {

    static org.apache.log4j.Logger logger = null;

    static {
        logger = org.apache.log4j.Logger.getLogger(UpdateMppThreadBak.class.getName());
    }

    @Override
    public void run() {
        logger.info("UpdateMppThread is running");
        while (true) {
            Connection mppcon = null;
            PreparedStatement ps = null;
            ArrayList<Map> jsonList = null;
            try {
                jsonList = new ArrayList<>(50);
                for (int i = 0; i < 50; ++i) {
                    logger.info("GlobalParameters.mppQueue.size()" + GlobalParameters.mppQueue.size());
                    Map str = GlobalParameters.mppQueue.poll(500, TimeUnit.MILLISECONDS);
                    if (null == str) {
                        logger.info("mppQueue is null ");
                        Thread.sleep(3000);
                        break;
                    }

                    jsonList.add(str);
                    logger.debug("strstrstrstrstrstrstr" + str + "________" + str.get("userid").toString());
                }
                if (jsonList.size() == 0) {
                    logger.info("updateQueue is null" + jsonList.toString() + " " + jsonList.size());
                    Thread.sleep(3000);
                    continue;
                }
                Long start = System.currentTimeMillis();
                for (int j = 0; j < 10; j++) {
                    try {
                        mppcon = MppJdbcPool_dbcp.getConnection();
                        if (mppcon != null) {
                            break;
                        }

                    } catch (Exception e) {
                        logger.error("mpp num " + j + " error " + e, e);
                        Thread.sleep(3000);
                    }
                }
                if (null == mppcon) {
                    logger.info("mppcon is null ");
                }
                int count = 0;
                for (Map map : jsonList) {
                    Long time = Long.valueOf(map.get("startTime").toString());
                    if ((System.currentTimeMillis() - time) > 172800000) {
                        logger.info("the opid select all mpp is null userid: " + map.get("userid") + " ct: " + map.get("ct") + " groupid: " + map.get("groupid"));
                    }
                    Long stime = System.currentTimeMillis();
                    String sql = "select m_type,m_content,u_name,u_send_ip,u_loc_county,u_loc_province,m_mm_id,m_mm_feature,m_dom_for,m_country_code,m_mm_url from tp_wxq_entire where u_ch_id=" + map.get("userid") + " and m_chat_room=" + map.get("groupid") + " and m_ch_id='" + map.get("ct") + "';";
//                    String sql = "select m_type,m_content,u_name,u_send_ip,u_loc_county,u_loc_province,m_mm_id,m_mm_feature,m_dom_for,m_country_code,m_mm_url from tp_wxq_entire where u_ch_id=" + map.get("userid") + " and m_chat_room=" + map.get("groupid") + " and m_ch_id='" + 000 + "';";
                    logger.info("the mpp select Sql is : " + sql);
                    Statement sele = mppcon.createStatement();
                    ResultSet rs = null;
                    try {
                        rs = sele.executeQuery(sql);
                    } catch (Exception e) {
                        logger.error(e);
                        String updatesql = "update tp_wxq_media_test set m_recall_count=cast(m_recall_count+1 as int) where u_ch_id=" + map.get("userid") + " and m_chat_room=" + map.get("groupid") + " and m_ch_id='" + map.get("ct") + "';";
                        ps = mppcon.prepareStatement(updatesql);
                        ps.executeUpdate();
                        GlobalParameters.retryQueue.put(map);
                        continue;
                    }

                    logger.info("ResultSet " + rs.getMetaData().getColumnCount());
                    List<Map> update = new ArrayList();
                    while (rs.next()) {
                        try {
                            Map result = new HashMap<>();
                            result.put("m_type", rs.getInt("m_type"));
                            if (null == rs.getString("m_content")) {
                                result.put("m_content", rs.getString("m_content"));
                            } else {
                                result.put("m_content", "");
                            }
                            result.put("u_name", rs.getString("u_name"));
                            result.put("u_send_ip", rs.getString("u_send_ip"));
                            result.put("u_loc_county", rs.getInt("u_loc_county"));
                            result.put("u_loc_province", rs.getInt("u_loc_province"));
                            result.put("m_mm_id", rs.getLong("m_mm_id"));
                            if (null == rs.getString("m_mm_feature")) {
                                result.put("m_mm_feature", rs.getString("m_mm_feature"));
                            } else {
                                result.put("m_mm_feature", "");
                            }
                            result.put("m_dom_for", rs.getInt("m_dom_for"));
                            result.put("m_country_code", rs.getInt("m_country_code"));
                            if (null == rs.getString("m_mm_url")) {
                                result.put("m_mm_url", rs.getString("m_mm_url"));
                            } else {
                                result.put("m_mm_url", "");
                            }
                            logger.info("result " + result.toString());
                            update.add(result);
                            count++;
                        } catch (Exception e) {
                            logger.error(e, e);
                        }
                    }
                    logger.info(" select all mpp time " + (System.currentTimeMillis() - stime));
                    if (update.size() == 0) {
                        logger.info("no select content");
                        String updatesql = "update tp_wxq_media_test set m_recall_count=cast(m_recall_count+1 as int) where u_ch_id=" + map.get("userid") + " and m_chat_room=" + map.get("groupid") + " and m_ch_id='" + map.get("ct") + "';";
                        ps = mppcon.prepareStatement(updatesql);
                        ps.executeUpdate();
                        GlobalParameters.retryQueue.put(map);
                        continue;
                    }
                    for (Map up : update) {
                        String updataSql = "Update tp_wxq_media_test set m_recall_count=1 ,m_type=" + Integer.valueOf(up.get("m_type").toString()) + ",m_content='" + up.get("m_content").toString() + "',u_name='" + up.get("u_name").toString() + "',u_send_ip='" + up.get("u_send_ip").toString() + "',u_loc_county=" + Integer.valueOf(up.get("u_loc_county").toString()) + ",u_loc_province=" + Integer.valueOf(up.get("u_loc_province").toString()) + ",m_mm_id=" + up.get("m_mm_id").toString() + ",m_mm_feature='" + up.get("m_mm_feature").toString() + "',m_dom_for=" + Integer.valueOf(up.get("m_dom_for").toString()) + ",m_country_code=" + Integer.valueOf(up.get("m_country_code").toString()) + ",m_mm_url='" + up.get("m_mm_url").toString() + "'where u_ch_id=" + map.get("userid") + " and m_chat_room=" + map.get("groupid") + " and m_ch_id='" + map.get("ct") + "';";
                        logger.info("updateSql is : " + updataSql);
                        ps = mppcon.prepareStatement(updataSql);
                        ps.executeUpdate();
                    }
                    logger.info(" update new mpp time " + (System.currentTimeMillis() - stime));

                }

//                int[] d = ps.executeBatch();
//                mppcon.commit();
                logger.info("update mpp sucess time: " + (System.currentTimeMillis() - start) + " ms count num: " + count);
                ps.close();
                MppJdbcPool_dbcp.closeConn(mppcon);

            } catch (Exception e) {
                logger.error("mpp update error " + e, e);
            } finally {
                if (mppcon != null) {
                    MppJdbcPool_dbcp.closeConn(mppcon);
                }
            }
        }

    }

    private static Map<String, String> getResultMap(ResultSet rs) throws SQLException {
        Map<String, String> hm = new HashMap<String, String>();
        ResultSetMetaData rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        logger.info("count " + count);
        for (int i = 1; i <= count; i++) {
            String key = rsmd.getColumnLabel(i);
            String value = rs.getString(i);
            hm.put(key, value);
        }
        return hm;
    }

}
